package com.atguigu.lease.common.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "minio")//容器创建配置对象时 会自动使用minio前缀匹配配置文件中的属性设置给自己的成员属性
@Data //自动设置属性 需要有getter方法
public class MinioConfig {
    /*
        抽取minio配置参数：
            endpoint: http://192.168.123.100:9000
            accessKey: minioadmin
            secretKey: minioadmin
            bucket: stgy
     */
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucket;
    @Bean
    public MinioClient minioClient() throws Exception {
        //1、创建minio客户端
        MinioClient minioClient = MinioClient.builder()
                //minio服务地址
                .endpoint(this.endpoint)
                //minio账号密码
                .credentials(accessKey,secretKey)
                .build();
        //2、判断需要使用的桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucket)
                .build());
        if (!exists) {
            //桶不存在，新建桶
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucket)
                    .build());
            //桶的权限默认 private读写
            //修改桶的权限为 公共读 私有写
            String policy = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(bucket); //使用bucket的值 填充字符串的占位符 最后返回字符串

            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucket)
                    .config(policy)
                    .build());
        }
        return minioClient;
    }
}
